<script setup lang="ts">
 import { ref, inject, useSlots, watch } from 'vue'
 import { hideLoading, msg, showLoading } from '@/utils/tools'
 const $Prefix = inject('$Prefix')
 const $emit = defineEmits(['update:modelValue'])
 const slots = useSlots()
 const props = defineProps({
   maxCount:{
     type:Number,
     default:10
   },
   multiple:{
     type:Boolean,
     default:true
   },
   modelValue:{
     type:Array,
     default:[]
   }
 })
 const fileList = ref(props.modelValue)
 // 删除图片
 const deletePic = (event:any) => {
   fileList.value.splice(event.index, 1);
   $emit('update:modelValue',fileList.value)
 };

 // 新增图片
 const afterRead = async (event:any) => {
   // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
   let lists = [].concat(event.file);
   let fileListLen = fileList.value.length;
   // lists.map((item:any) => {
   //   fileList.value.push({
   //     ...item,
   //     status: 'uploading',
   //     message: '上传中',
   //   });
   // });
   showLoading('上传中')
   for (let i = 0; i < lists.length; i++) {
     const result = await uploadFilePromise(lists[i].url);
     let item:any = fileList.value[fileListLen];
     const resultObj = JSON.parse(result as string)
     if(resultObj.code == 200){
       fileList.value.splice(fileListLen, 1, {
         ...resultObj.data,
         status: 'success',
         message: '',
         url: resultObj.data.fullUrl,
         originalUrl:resultObj.data.url
       });
       fileListLen++;
     }else{
       fileList.value.splice(fileListLen, 1);
     }
   }
   hideLoading()
   $emit('update:modelValue',fileList.value)
 };

 const uploadFilePromise = (url:any) => {

   return new Promise((resolve, reject) => {
     uni.uploadFile({
       url: $Prefix+'/api/mobile/file/public/upload', // 仅为示例，非真实的接口地址
       filePath: url,
       name: 'file',
       success: (res:any) => {
         if(res.statusCode == 200){
           setTimeout(() => {
             resolve(res.data);
           }, 1000);
         }else{
           setTimeout(() => {
             resolve(false);
           }, 1000);
           msg('上传失败,请重新上传')
         }

       },
     });
   });
 };

 watch(() => props.modelValue, (newValue) => {
   fileList.value = newValue
 })
</script>

<template>
  <up-upload
    :fileList="fileList"
    @afterRead="afterRead"
    @delete="deletePic"
    :multiple="props.multiple"
    :maxCount="props.maxCount"
    v-if="!slots.default"
  />
  <up-upload
    :fileList="fileList"
    @afterRead="afterRead"
    @delete="deletePic"
    :multiple="props.multiple"
    :maxCount="props.maxCount"
    v-else
  >
    <slot></slot>
  </up-upload>
</template>

<style scoped lang="scss">

</style>
